﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AGR.Model;
using AGR.Services.Course;
using AGR.Services.Course.Contract;
using AGR.Services.Employee;
using AGR.Services.Employee.Contract;
using AGR.Services;

namespace AGR.Web.Controls.Form.DetailForm
{
    public partial class CourseDetail : System.Web.UI.UserControl
    {
        private ICourseService _courseService = new CourseService();
        private ISubjectService _subjectService = new SubjectService();
        private ICourseDetailsService _courseDetailsService = new CourseDetailsService();
        private IEmployeeService _employeeService = new EmployeeService();
        private ITrainerService _trainerService = new TrainerService();

        protected void Page_Load(object sender, EventArgs e)
        { }

        #region Public Methods

        public void LoadDetail(string primaryKey)
        {
            var entity = _courseService.GetCourse(primaryKey);

            txtCourseCode.Text = primaryKey;
            txtCourse.Text = entity.CourseName;
            txtAccreditation.Text = entity.AccreditationNumber;
            txtCategory.Text = entity.Category;
            txtCertificate.Text = entity.CertificateType;

            txtDateCreated.Text = entity.DateCreated.ToString   ();
            txtUserCreated.Text = entity.UserCreated;
            txtDateModified.Text = entity.DateModified.ToString();
            txtUserModified.Text = entity.UserModified;

            this.LoadGrid();
        }

        public void ClearDetail()
        {
            this.Clear();
            SubjectGridView.ShowFooter = false;
            SubjectGridView.EditIndex = -1;
        }

        #endregion

        #region Button Methods

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            SubjectGridView.ShowFooter = true;
            SubjectGridView.EditIndex = -1;

            this.LoadGrid();

            DropDownList ddlSubjectTitle = (DropDownList)SubjectGridView.FooterRow.FindControl("ddlSubjectTitle");
            DropDownList ddlEmployeeTitle = (DropDownList)SubjectGridView.FooterRow.FindControl("ddlEmployeeTitle");
            LoadList(ddlSubjectTitle, ddlEmployeeTitle);
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            bool selected = false;
            int selectCount = 0;
            int deleteCount = 0;
            string succesMessages = string.Empty;
            string errorMessages = string.Empty;
            string courseCode = txtCourseCode.Text;

            IList<ActionResult> results = new List<ActionResult>();

            for (int i = 0; i < SubjectGridView.Rows.Count; i++)
            {
                var row = SubjectGridView.Rows[i];
                bool isChecked = ((CheckBox)row.FindControl("chkSelect")).Checked;

                if (isChecked)
                {
                    var codes = SubjectGridView.DataKeys[i].Values;
                    string subjectCode = codes["SubjectCode"].ToString();
                    string employeeCode = codes["EmployeeCode"].ToString();
                    results.Add(_courseDetailsService.DeleteCourseSubject(courseCode, subjectCode));
                    selected = true;
                    selectCount++;
                }
            }

            if (selected == false)
            {
                ucMessage.ShowMessage("Please select records for deletion and try again.", Message.Message.MessageType.Information);
                return;
            }

            foreach (ActionResult result in results)
            {
                if (result.Success)
                {
                    succesMessages = result.Message;
                    deleteCount++;
                }
                else
                    errorMessages = result.Message;
            }

            if (!string.IsNullOrEmpty(succesMessages))
                ucMessage.ShowMessage(succesMessages, Message.Message.MessageType.Success);

            if (!string.IsNullOrEmpty(errorMessages))
                ucMessage.ShowMessage(errorMessages + " " + (selectCount - deleteCount) + " records deleted.", Message.Message.MessageType.Error);

            SubjectGridView.EditIndex = -1;
            this.LoadGrid();
        }

        #endregion

        #region DropDownList Methods

        #endregion

        #region GridView Methods

        protected void SubjectGridView_OnRowCommand(object sender, CommandEventArgs e)
        {
            if (e.CommandName == "Insert")
            {
                string courseCode = txtCourseCode.Text;
                string subjectCode = ((DropDownList)SubjectGridView.FooterRow.FindControl("ddlSubjectTitle")).SelectedValue.ToString();
                string employeeCode = ((DropDownList)SubjectGridView.FooterRow.FindControl("ddlEmployeeTitle")).SelectedValue.ToString();

                var exists = _courseDetailsService.GetCourseSubject(courseCode, subjectCode);

                if (exists != null)
                {
                    ucMessage.ShowMessage("Your action could not be completed. A record with subject code (" + subjectCode + ") already exists for this course.", Message.Message.MessageType.Warning);
                    return;
                }

                var result = _courseDetailsService.AddCourseSubject(courseCode, subjectCode, employeeCode, "TestUser");

                if (result.Success)
                {
                    ucMessage.ShowMessage(result.Message, Message.Message.MessageType.Success);
                    SubjectGridView.ShowFooter = false;
                    SubjectGridView.EditIndex = -1;
                    this.LoadGrid();
                }
                else
                    ucMessage.ShowMessage(result.Message, Message.Message.MessageType.Error);
            }
            else if (e.CommandName == "CancelInsert")
            {
                ucMessage.ClearMessage();
                SubjectGridView.ShowFooter = false;
                SubjectGridView.EditIndex = -1;
                this.LoadGrid();
            }
        }

        protected void SubjectGridView_RowEditing(object sender, GridViewEditEventArgs e)
        {
            ucMessage.ClearMessage();

            SubjectGridView.ShowFooter = false;
            SubjectGridView.EditIndex = e.NewEditIndex;
            this.LoadGrid();

            DropDownList ddlEmployeeTitle = (DropDownList)SubjectGridView.Rows[e.NewEditIndex].FindControl("ddlEmployeeTitle");
            LoadList(ddlEmployeeTitle);
        }

        protected void SubjectGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            SubjectGridView.EditIndex = -1;
            this.LoadGrid();
        }

        protected void SubjectGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            string courseCode = txtCourseCode.Text;
            string subjectCode = ((Label)SubjectGridView.Rows[e.RowIndex].FindControl("lblSubjectCode")).Text; 
            string employeeCode = ((DropDownList)SubjectGridView.Rows[e.RowIndex].FindControl("ddlEmployeeTitle")).SelectedValue.ToString();

            var entity = _courseDetailsService.GetCourseSubject(x => x.CourseCode == courseCode &&
                                                                     x.SubjectCode == subjectCode);

            entity.EmployeeCode = employeeCode;
            entity.UserModified = "TestUser";

            var result = _courseDetailsService.UpdateCourseSubject(entity);

            if (result.Success)
            {
                ucMessage.ShowMessage(result.Message, Message.Message.MessageType.Success);
                SubjectGridView.EditIndex = -1;
                this.LoadGrid();
            }
            else
                ucMessage.ShowMessage(result.Message, Message.Message.MessageType.Error);
        }

        protected void SubjectGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            SubjectGridView.PageIndex = e.NewPageIndex;
            SubjectGridView.EditIndex = -1;
            this.LoadGrid();
        }

        #endregion

        #region Private Methods

        private void LoadGrid()
        {
            var subjectDetails = (from fact in _courseDetailsService.GetAllCourseSubjects(txtCourseCode.Text)
                                  join subject in _subjectService.GetAllSubjects() on fact.SubjectCode equals subject.SubjectCode
                                  select new
                                  {
                                      SubjectCode = fact.SubjectCode,
                                      Type = subject.Type,
                                      Title = subject.Title,
                                      Description = subject.Description,
                                      NQFLevel = subject.NQFLevel,
                                      Credits = subject.Credits,
                                      EmployeeCode = fact.EmployeeCode
                                  }).ToList();

            if (subjectDetails.Count == 0)
            {
                int? nqf = 0;
                subjectDetails.Add(new { SubjectCode = "", Type = "", Title = "", Description = "", NQFLevel = nqf, Credits = nqf, EmployeeCode = "" });
                SubjectGridView.ShowFooter = true;
                SubjectGridView.EditIndex = -1;

                SubjectGridView.DataSource = subjectDetails;
                SubjectGridView.DataBind();
                SubjectGridView.Rows[0].Visible = false;

                DropDownList ddlSubjectTitle = (DropDownList)SubjectGridView.FooterRow.FindControl("ddlSubjectTitle");
                DropDownList ddlEmployeeTitle = (DropDownList)SubjectGridView.FooterRow.FindControl("ddlEmployeeTitle");
                LoadList(ddlSubjectTitle, ddlEmployeeTitle);
            }
            else
            {
                SubjectGridView.DataSource = subjectDetails;
                SubjectGridView.DataBind();
            }
        }

        private void LoadList(DropDownList ddlSubjectTitle, DropDownList ddlEmployeeTitle)
        {
            var subjectList = (from list in _subjectService.GetAllSubjects()
                                select new { SubjectCode = list.SubjectCode, Description = list.Title + " - " + list.SubjectCode }).ToList();

            var employeeList = (from list in _employeeService.GetAllEmployees(x => x.IsTrainer == true)
                                select new { EmployeeCode = list.EmployeeCode, Description = list.FirstName + " " + list.LastName + " - " + list.EmployeeCode }).ToList();

            ddlSubjectTitle.DataSource = subjectList;
            ddlSubjectTitle.DataTextField = "Description";
            ddlSubjectTitle.DataValueField = "SubjectCode";
            ddlSubjectTitle.DataBind();

            ddlEmployeeTitle.DataSource = employeeList;
            ddlEmployeeTitle.DataTextField = "Description";
            ddlEmployeeTitle.DataValueField = "EmployeeCode";
            ddlEmployeeTitle.DataBind();
        }

        private void LoadList(DropDownList ddlEmployeeTitle)
        {
            var employeeList = (from list in _employeeService.GetAllEmployees(x => x.IsTrainer == true)
                                select new { EmployeeCode = list.EmployeeCode, Description = list.FirstName + " " + list.LastName + " - " + list.EmployeeCode }).ToList();

            ddlEmployeeTitle.DataSource = employeeList;
            ddlEmployeeTitle.DataTextField = "Description";
            ddlEmployeeTitle.DataValueField = "EmployeeCode";
            ddlEmployeeTitle.DataBind();
        }

        private void Clear()
        {
            ucMessage.ClearMessage();

            txtCourseCode.Text = string.Empty;
            txtCourse.Text = string.Empty;
            txtAccreditation.Text = string.Empty;
            txtCategory.Text = string.Empty;
            txtCertificate.Text = string.Empty;

            txtDateCreated.Text = string.Empty;
            txtUserCreated.Text = string.Empty;
            txtDateModified.Text = string.Empty;
            txtUserModified.Text = string.Empty;
        }

        #endregion
    }
}